package models

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

// Config 配置
type Config struct {
	User     string
	Password string
	Host     string
	Name     string
}

var (
	db *gorm.DB
)

// Setup initializes the database instance
// 安装程序初始化数据库实例
func Setup(cfg Config) error {
	var err error
	db, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
		cfg.User,
		cfg.Password,
		cfg.Host,
		cfg.Name))
	if err != nil {
		return err
	}
	db.SingularTable(true)
	db.DB().SetMaxIdleConns(56)
	db.DB().SetMaxOpenConns(128)
	return nil
}

// CloseDB closes database connection (unnecessary)
func CloseDB() {
	defer db.Close()
}
